home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C04 / CppLib.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.6 KB  |  66 lines

  1. //: C04:CppLib.cpp {O}
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // C library converted to C++
  7. // Declare structure and functions:
  8. #include "CppLib.h"
  9. #include <iostream>
  10. #include <cassert>
  11. using namespace std;
  12. // Quantity of elements to add
  13. // when increasing storage:
  14. const int increment = 100;
  15.  
  16. void Stash::initialize(int sz) {
  17.   size = sz;
  18.   quantity = 0;
  19.   storage = 0;
  20.   next = 0;
  21. }
  22.  
  23. int Stash::add(const void* element) {
  24.   if(next >= quantity) // Enough space left?
  25.     inflate(increment);
  26.   // Copy element into storage,
  27.   // starting at next empty space:
  28.   int startBytes = next * size;
  29.   unsigned char* e = (unsigned char*)element;
  30.   for(int i = 0; i < size; i++)
  31.     storage[startBytes + i] = e[i];
  32.   next++;
  33.   return(next - 1); // Index number
  34. }
  35.  
  36. void* Stash::fetch(int index) {
  37.   // Check index boundaries:
  38.   assert(0 <= index && index < next);
  39.   // Produce pointer to desired element:
  40.   return &(storage[index * size]);
  41. }
  42.  
  43. int Stash::count() {
  44.   return next; // Number of elements in CStash
  45. }
  46.  
  47. void Stash::inflate(int increase) {
  48.   assert(increase > 0);
  49.   int newQuantity = quantity + increase;
  50.   int newBytes = newQuantity * size;
  51.   int oldBytes = quantity * size;
  52.   unsigned char* b = new unsigned char[newBytes];
  53.   for(int i = 0; i < oldBytes; i++)
  54.     b[i] = storage[i]; // Copy old to new
  55.   delete []storage; // Old storage
  56.   storage = b; // Point to new memory
  57.   quantity = newQuantity;
  58. }
  59.  
  60. void Stash::cleanup() {
  61.   if(storage != 0) {
  62.    cout << "freeing storage" << endl;
  63.    delete []storage;
  64.   }
  65. } ///:~
  66.